package com.heima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.tlias.anno.Log;
import com.heima.tlias.controller.request.StudentQueryRequest;
import com.heima.tlias.dao.StudentMapper;
import com.heima.tlias.pojo.Student;
import com.heima.tlias.service.StudentService;
import com.heima.tlias.utils.PageBean;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author Administrator
 * @Date 2024/5/4
 **/
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {

    private final StudentMapper studentMapper;

    @Override
    public PageBean<Student> queryByPage(StudentQueryRequest request) {
        PageHelper.startPage(request.getPage(), request.getPageSize());
        Page<Student> page = studentMapper.queryList(request);
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    @Override
    @Log
    public void insert(Student student) {
        student.setViolationCount(0);
        student.setViolationScore(0);
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insert(student);
    }

    @Override
    public Student queryById(Integer id) {
        return studentMapper.queryById(id);
    }

    @Override
    @Log
    public void updateById(Student student) {
        studentMapper.updateById(student);
    }

    @Override
    @Log
    public void deleteByIds(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return;
        }
        studentMapper.deleteByIds(ids);
    }

    @Override
    @Log
    public void violation(Integer id, Integer score) {
        Student student = studentMapper.queryById(id);
        if (student==null){
            throw new RuntimeException("学员不存在");
        }
        student.setViolationCount(student.getViolationCount()+1);
        student.setViolationScore(student.getViolationScore()+score);
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.updateById(student);
    }
}
